package com.x.client.utils

import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.view.Gravity
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.gg.utils.AppManager
import com.gg.utils.isPhoneNum
import com.gg.utils.toast
import com.gg.widget.LoadUtils
import com.gg.widget.dialog.AlertDialog
import com.jakewharton.rxbinding2.view.RxView
import com.jakewharton.rxbinding2.widget.RxTextView
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import com.x.client.App
import com.x.client.R
import com.x.client.net.ApiFactory
import com.x.client.net.Composers
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.Observables
import java.util.concurrent.TimeUnit

/**
 * Creator : GG
 * Date    : 2018/3/27
 * Mail    : gg.jin.yu@gmai.com
 * Explain :
 */
@Interceptor(priority = 8, name = "拦截器")
class ClientInterceptor : IInterceptor {

    private var context: Context? = null

    private var phone = ""
    private var code = ""

    private var agree = false

    private lateinit var loginDialogView: View
    private lateinit var editPhone: EditText
    private lateinit var editPassword: EditText
    private lateinit var close: View
    private lateinit var login: TextView
    private lateinit var loginWithRegister: TextView
    private lateinit var getCode: TextView
    private lateinit var clearEdit: View

    private lateinit var loginDialog: AlertDialog

    private val unAgreeDrawable: Drawable? by lazy {
        ContextCompat.getDrawable(AppManager.currentActivity(), R.drawable.ic_oval_grey)!!.apply {
            setBounds(0, 0, minimumHeight, minimumWidth)
        }
    }
    private val agreeDrawable: Drawable? by lazy {
        ContextCompat.getDrawable(AppManager.currentActivity(), R.drawable.ic_check_oval_orange)!!.apply {
            setBounds(0, 0, minimumHeight, minimumWidth)
        }
    }

    override fun process(postcard: Postcard, callback: InterceptorCallback) {

        Observable.just(postcard)
                .map { return@map it.path }
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (App.instance.getUser() == null && getCheck(path = it)) {

                        setLoginDialog()
                    } else {
                        callback.onContinue(postcard)
                    }
                }
    }

    private fun setLoginDialog() {

        if (!this::loginDialogView.isInitialized)
            loginDialogView = AppManager.currentActivity().layoutInflater.inflate(R.layout.dialog_login, null, false)

        if (!this::editPhone.isInitialized && this::loginDialogView.isInitialized)
            editPhone = loginDialogView.findViewById(R.id.editPhone)

        if (!this::editPassword.isInitialized && this::loginDialogView.isInitialized)
            editPassword = loginDialogView.findViewById(R.id.editPassword)

        if (!this::close.isInitialized && this::loginDialogView.isInitialized)
            close = loginDialogView.findViewById<View>(R.id.close)

        if (!this::login.isInitialized && this::loginDialogView.isInitialized)
            login = loginDialogView.findViewById(R.id.login)

        if (!this::loginWithRegister.isInitialized && this::loginDialogView.isInitialized)
            loginWithRegister = loginDialogView.findViewById<TextView>(R.id.loginWithRegister)

        if (!this::getCode.isInitialized && this::loginDialogView.isInitialized)
            getCode = loginDialogView.findViewById(R.id.getCode)

        if (!this::clearEdit.isInitialized && this::loginDialogView.isInitialized)
            clearEdit = loginDialogView.findViewById(R.id.clearEdit)

        if (this::getCode.isInitialized) {
//            getCode.isEnabled = false
            RxView.clicks(getCode)
                    .throttleFirst(500, TimeUnit.MICROSECONDS)
                    .subscribe {
                        LoadUtils.show(AppManager.currentActivity())
                        ApiFactory.getClientApi()
                                .getLoginValidCode(userMobile = phone)
                                .compose(Composers.composeWithoutResponse())
                                .subscribe({
                                    LoadUtils.hidden()
                                    AppManager.currentActivity().toast(it.msg)
                                }, {
                                    LoadUtils.hidden()
                                    AppManager.currentActivity().toast("获取验证码失败")
                                })
                    }
        }
        if (!this::loginDialog.isInitialized && this::loginDialogView.isInitialized) {
            loginDialog =
                    AlertDialog.Builder(AppManager.currentActivity())
                            .setContentView(loginDialogView)
                            .setGravity(Gravity.TOP)
                            .setVerticalMargin(300)
                            .setCancelable(false)
                            .create()
        }


//        if (this::editPhone.isInitialized)
//            RxTextView.textChanges(editPhone)
//                    .skipInitialValue()
//                    .debounce(200, TimeUnit.MICROSECONDS)
//                    .subscribe {
//                        when {
//                            it.isEmpty() -> clear.visibility = View.INVISIBLE
//                            it.length == 11 -> {
//                                clear.visibility = View.VISIBLE
//                                getCode.setTextColor(ContextCompat.getColor(AppManager.getInstance().currentActivity(), R.color.text_orange))
//                                getCode.isEnabled = true
//                            }
//                            else -> {
//                                clear.visibility = View.VISIBLE
//                                getCode.setTextColor(ContextCompat.getColor(AppManager.getInstance().currentActivity(), R.color.text_grey))
//                                getCode.isEnabled = false
//                            }
//                        }
//                        phone = it.toString()
//                    }
//
//        if (this::editPassword.isInitialized) {
//            RxTextView.textChanges(editPassword)
//                    .skipInitialValue()
//                    .debounce(200, TimeUnit.MICROSECONDS)
//                    .subscribe {
//                        code = it.toString()
//                    }
//        }

        if (this::login.isInitialized && this::editPhone.isInitialized && this::editPassword.isInitialized) {
            val phoneObservable = RxTextView.textChanges(editPhone)

            val codeObservable = RxTextView.textChanges(editPassword)

            Observables.combineLatest(phoneObservable, codeObservable) { t1, t2 ->
                phone = t1.toString()
                code = t2.toString()
                when {
                    t1.isEmpty() -> {
                        clearEdit.visibility = View.INVISIBLE
                        getCode.setTextColor(ContextCompat.getColor(AppManager.currentActivity(), R.color.text_grey))
                        getCode.isEnabled = false
                    }
                    t1.length == 11 -> {
                        if (!phone.isPhoneNum()) {
                            App.instance.toast("手机号格式不正确")
                        }

                        clearEdit.visibility = View.VISIBLE
                        getCode.setTextColor(ContextCompat.getColor(AppManager.currentActivity(), R.color.text_orange))
                        getCode.isEnabled = true
                    }
                    else -> {
                        clearEdit.visibility = View.VISIBLE
                        getCode.setTextColor(ContextCompat.getColor(AppManager.currentActivity(), R.color.text_grey))
                        getCode.isEnabled = false
                    }
                }



                if (phone.isPhoneNum() && code.length == 6) {
                    login.isEnabled = true
                    login.background = ContextCompat.getDrawable(AppManager.currentActivity(), R.drawable.bg_text_login)
                } else {
                    login.isEnabled = false
                    login.background = ContextCompat.getDrawable(AppManager.currentActivity(), R.drawable.bg_text_login_grey)
                }
            }
                    .compose((AppManager.currentActivity() as RxAppCompatActivity).bindToLifecycle())
                    .subscribe {
                        RxView.clicks(login)
                                .throttleFirst(500, TimeUnit.MICROSECONDS)
                                .compose((AppManager.currentActivity() as RxAppCompatActivity).bindToLifecycle())
                                .subscribe {
                                    if (agree) {
                                        LoadUtils.show(AppManager.currentActivity())
                                        ApiFactory.getClientApi()
                                                .login(userMobile = phone,
                                                        validateCode = code)
                                                .compose(Composers.handleError())
                                                .subscribe({
                                                    LoadUtils.hidden()
                                                    App.instance.setUser(it)
                                                    loginDialog.dismiss()

                                                }, {
                                                    LoadUtils.hidden()
                                                })
                                    } else {
                                        App.instance.toast("需要勾选登陆授权同步注册才能够登陆")
                                    }
                                }
                    }


            if (this::close.isInitialized && this::loginDialog.isInitialized) {
                RxView.clicks(close)
                        .throttleFirst(1, TimeUnit.SECONDS)
                        .compose((AppManager.currentActivity() as RxAppCompatActivity).bindToLifecycle())
                        .subscribe {
                            loginDialog.dismiss()
                        }
            }
            if (this::clearEdit.isInitialized && this::editPhone.isInitialized) {
                RxView.clicks(clearEdit)
                        .throttleFirst(500, TimeUnit.MICROSECONDS)
                        .debounce(500, TimeUnit.MICROSECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .compose((AppManager.currentActivity() as RxAppCompatActivity).bindToLifecycle())
                        .subscribe {
                            editPhone.setText("")
                        }
            }

            if (this::loginWithRegister.isInitialized) {
                RxView.clicks(loginWithRegister)
                        .throttleFirst(500, TimeUnit.MICROSECONDS)
                        .subscribe {
                            agree = !agree
                            loginWithRegister.setCompoundDrawables(if (agree) agreeDrawable else unAgreeDrawable, null, null, null)
                        }
            }

            if (this::loginDialog.isInitialized) {
                loginDialog.show()
            }
        }

    }

    private fun getCheck(path: String): Boolean =
            when (path) {
                RouterClass.message,
                RouterClass.feedback,
                RouterClass.carSubscribe,
                RouterClass.saleCar -> true

                else -> false
            }

    override fun init(context: Context?) {
        this.context = context?.applicationContext
    }
}